#ifndef __M_CONNECTION_H__
#define __M_CONNECTION_H__
#include "protobuf/codec/codec.h"
#include "protobuf/codec/dispatcher.h"
#include "muduo/base/Logging.h"
#include "muduo/base/Mutex.h"
#include "muduo/net/EventLoop.h"
#include "muduo/net/TcpServer.h"
#include "muduo/net/TcpClient.h"
#include "muduo/base/CountDownLatch.h"
#include "muduo/net/EventLoopThread.h"


#include "mq_channel.hpp"
#include "../mqcommon/mq_threadpool.hpp"
#include "../mqcommon/mq_loger.hpp"
#include "mq_worker.hpp"

namespace mq{

class Connection{
public:
    using ptr = std::shared_ptr<Connection>;

    Connection(std::string sip,int16_t sport,AsyncWorker::ptr& worker):
    _client(worker->loopthread.startLoop(),muduo::net::InetAddress(sip,sport),"TcpClient"),
    _dispatcher(std::bind(&Connection::onknowMessage,this,std::placeholders::_1,std::placeholders::_2,std::placeholders::_3)),
    _codec(std::make_shared<ProtobufCodec>(std::bind(&ProtobufDispatcher::onProtobufMessage,&_dispatcher,std::placeholders::_1,std::placeholders::_2,std::placeholders::_3))),
    _latch(1),
    _worker(worker),
    _channel_manager(std::make_shared<ChannelManager>())
    {
        _dispatcher.registerMessageCallback<basicCommonResponse>(std::bind(&Connection::basicResponse,this,std::placeholders::_1,std::placeholders::_2,std::placeholders::_3));
        _dispatcher.registerMessageCallback<basicConsumeResponse>(std::bind(&Connection::consumeResponse,this,std::placeholders::_1,std::placeholders::_2,std::placeholders::_3));


        _client.setConnectionCallback(std::bind(&Connection::onConnection,this,std::placeholders::_1));
        _client.setMessageCallback(std::bind(&ProtobufCodec::onMessage,_codec.get(),std::placeholders::_1,std::placeholders::_2,std::placeholders::_3));
        

        _client.connect();//建立连接
        _latch.wait();//等待连接
    }
    Channel::ptr openChannel(){
        Channel::ptr channel = _channel_manager->create(_codec,_conn);
        bool ret = channel->openChannel();
        if(ret == false){
            DLOG("打开信道失败！");
            return Channel::ptr();
        }
        DLOG("打开信道%s 成功！",channel->cid().c_str());
        return channel;
    }

    void closeChannel(const Channel::ptr& channel){
        channel->closeChannel();
        _channel_manager->remove(channel->cid());
    }
private:
    void basicResponse(const muduo::net::TcpConnectionPtr& conn,
                                const basicCommonResponsePtr& resp,
                                muduo::Timestamp){
        //找到信道，通过信道管理
        Channel::ptr channel = _channel_manager->get(resp->cid());
        if(channel.get() == nullptr){
            DLOG("未找到：%s 信道信息！",resp->cid().c_str());
            return ;
        }
        //将响应推送到信道响应hash中
        channel->putBasicResponse(resp);
    }  
    
    void consumeResponse(const muduo::net::TcpConnectionPtr& conn,
                                const basicConsumeResponsePtr& resp,
                                muduo::Timestamp){
        // DLOG("接收到consume响应!");                    
                    //找到信道，通过信道管理
        mq::Channel::ptr channel = _channel_manager->get(resp->cid());
        if(channel.get() == nullptr){
            DLOG("未找到信道信息！");
            return ;
        }

        _worker->pool.push([channel,resp](){
            //推送到线程池中的任务是：
            //消费
            channel->consume(resp);
        });
    }  
    void onConnection(const muduo::net::TcpConnectionPtr &conn){
        if(!conn->connected())
        {
            std::cout << "新连接关闭" << std::endl;
        }
        else
        {
            std::cout << "新连接成功" << std::endl;
            _latch.countDown();//当连接成功后，唤醒 
            _conn = conn;//注意别忘了！
        }   
    }   
    void onknowMessage(const muduo::net::TcpConnectionPtr& conn,
                                const MessagePtr& message,
                                muduo::Timestamp)
    {
        LOG_INFO << "onUnknownMessage: " << message->GetTypeName();
        conn->shutdown();
    }




private:
    ProtobufDispatcher _dispatcher;
    muduo::net::TcpClient _client;
    muduo::CountDownLatch _latch;//进行防止等待连接导致的阻塞
    muduo::net::TcpConnectionPtr _conn;

    ProtobufCodecPtr _codec;

    ChannelManager::ptr  _channel_manager;
    AsyncWorker::ptr _worker;
};

}
#endif